package GUI;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.ComponentOrientation;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Vector;

import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SpringLayout;
import javax.swing.border.LineBorder;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import javax.swing.text.MaskFormatter;

import net.sourceforge.jdatepicker.JDateComponentFactory;
import net.sourceforge.jdatepicker.impl.JDatePickerImpl;

import CommonGui.ColorRowRendererForTelOrder;
import CommonGui.MyComboBoxEditor;
import CommonGui.MyComboBoxRenderer;
import CommonGui.MyTableModelForTelOrdersJTable;
import CommonGui.NotEdditibleTable;
import DataObjects.ConstantObjects;
import Messages.MessageAddNewTelephoneOrder;
import Messages.MessageGetAllTelephoneOrdersForDate;
import Messages.MessageGetAllTelephoneOrdersForDateReply;
import Messages.MessageGetReportOnTablesOfWaiter;
import Messages.MessageGetReportOnTablesOfWaiterReply;
import Messages.MessageGetReportWaitersByDate;
import Messages.MessageGetReportWaitersByDateReply;
import Messages.MessageGetReportWorkHoursOfWaiter;
import Messages.MessageGetReportWorkHoursOfWaiterReply;
import Messages.MessageSavingReply;

/**
 * Class for creation window that  show report on sales JTable(ID,name,quantity tables,quantity persons,quantity menus) 
 * 
 */

public class PfReportOnSales extends JPanel {
	
	
	private MainMenu mainMenu;
	private Vector<Vector> reportWaiters;	
	
	private JPanel setDateForSearch;
	private JPanel detailsPanel;
	
	private DefaultTableModel dtm;
	private JTable tbl;
	
	private Vector<String> selectedRowVec=null;
	
	private String globalDate=null;
	
	private JDatePickerImpl newOrderDate;
	private JDatePickerImpl dateForSearchFrom ;
	private JDatePickerImpl dateForSearchTo ;
	
	private JButton refreshBtn;	
	
	private String FromDate=null;
	private String ToDate=null;
	
	private Vector<Vector> trying;
	
	PfReportOnTablesAndWaiter secondTablePanel;
	
	private String waiterID;
	private int flagReportFirstOrReportSecondOfThisWaiter;
	
	
	/**
	 * Method-structor
	 * @param mm
	 * @param reportWaiters - report on sales
	 */
	public PfReportOnSales(MainMenu mm, Vector<Vector> reportWaiters)
	{
		super();
		this.setLayout(new BorderLayout());
		this.mainMenu=mm;
		this.reportWaiters=reportWaiters;
		DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
		Date date = new Date();
		globalDate=dateFormat.format(date);
		initiliaze();
		
	}	
	
	
	private void initiliaze()
	{
		JScrollPane scrollPane = new JScrollPane(getTblReport());
		this.add(scrollPane,BorderLayout.CENTER);
		this.add( getSetDateForSearchPanel(),BorderLayout.NORTH);
	}
	
	
	/**
	 * Method for creation JTable tbl with report on sales
	 * @return JTable tbl
	 */
	private JTable getTblReport()
	{
		Vector <String> tblheader=new Vector<String>();
		
		tblheader.add("ID");
		tblheader.add("שם המלצר");
		tblheader.add("כמות שולחנות");
		tblheader.add("כמות לקוחות");
		tblheader.add("טעימות");
		tblheader.add("כמות היינות");
		tblheader.add("כמות שתיה קלה");
		tblheader.add("1");
		tblheader.add("2");
		
		dtm=new NotEdditibleTable(reportWaiters,tblheader);	 		
		tbl = new JTable(dtm);
		tbl.getTableHeader().setReorderingAllowed(false);                         //Not move columns
		DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
		centerRenderer.setHorizontalAlignment( JLabel.CENTER );
		for(int x=0;x<5;x++){
			tbl.getColumnModel().getColumn(x).setCellRenderer( centerRenderer );
	        }
		
		tbl.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
        TableColumn tm = tbl.getColumnModel().getColumn(0);
             					
		tbl.setBorder(new LineBorder(new Color(0, 0, 0), 1, true));
		tbl.setFont(new Font("David", Font.BOLD, 16));
		tbl.removeColumn(tbl.getColumnModel().getColumn(8));
		tbl.removeColumn(tbl.getColumnModel().getColumn(7));
		tbl.removeColumn(tbl.getColumnModel().getColumn(6));
		tbl.removeColumn(tbl.getColumnModel().getColumn(5));
		tbl.getTableHeader().setFont( new Font( "Arial" , Font.BOLD, 17 ));
		tbl.getTableHeader().setBackground(new Color(173,216,230));
		tbl.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS); 
	    tbl.setRowHeight(30);
		tbl.setFillsViewportHeight(true);
        tbl.setGridColor(new Color(25, 25, 112));
        tbl.setBackground(new Color(250, 235, 215));
        tbl.setForeground(new Color(0, 0, 0));
        tbl.setAutoCreateRowSorter(true);
             
        TableColumn col_6 = tbl.getColumnModel().getColumn(2);
        tbl.addMouseListener(new MouseAdapter() {
			   public void mouseClicked(MouseEvent e) {
			     if (e.getClickCount() == 1) {
			       JTable target = (JTable)e.getSource();
			       tbl.setColumnSelectionAllowed(true);        //Select only one cell
			       tbl.setRowSelectionAllowed(true);
			       int row = target.getSelectedRow();
			       int column = target.getSelectedColumn();
			       if(row!=-1)
			       {
			    	   selectedRowVec=(Vector<String>) dtm.getDataVector().get(row);
			       }
			     }
			     
			     if (e.getClickCount() == 2){
			    	   JTable target = (JTable)e.getSource();
				       tbl.setColumnSelectionAllowed(true);        //Select only one cell
				       tbl.setRowSelectionAllowed(true);
				       int row = target.getSelectedRow();
				       int column = target.getSelectedColumn();
				       if(row!=-1)
				       {
				    	   selectedRowVec=(Vector<String>) dtm.getDataVector().get(row);
				    	   int row_index=target.getSelectedRow();
				    	   int column_index=target.getSelectedColumn();
					       Vector<String> vec=(Vector<String>) dtm.getDataVector().get(row_index);
				       if(column_index==1)
				    	   {
				    	   waiterID=vec.get(0);
				    	   flagReportFirstOrReportSecondOfThisWaiter=1;
				    	   //flag show which report is necessary (on waiter or on table).column_index==1 necessary report on waiter
					    	   addReportOnWorkDaysOfWaiter(waiterID,flagReportFirstOrReportSecondOfThisWaiter);
				    	   }	
				       if(column_index==2)
			    	   {
			    		  waiterID=vec.get(0);
			    		  flagReportFirstOrReportSecondOfThisWaiter=2;
			    		//flag show which report is necessary(on waiter or on table).column_index==2 necessary report on table
				    	   addReportOnTablesOfWaiter(waiterID,flagReportFirstOrReportSecondOfThisWaiter);
			    	   }		   
					    	   
					        	   
				       }
			    	   
			    	//addChangeOrderPanel();
			         }
			      }
			   
			 });
        
         return tbl;
	}
	
	
	private JPanel getSetDateForSearchPanel()
	{
		setDateForSearch=new JPanel();
		setDateForSearch.setLayout(new BoxLayout(setDateForSearch, BoxLayout.Y_AXIS));
		setDateForSearch.add(getSearchDetails());
		return setDateForSearch;
	}
	
	
	private JPanel getDetailsPanel(Vector<Vector> reportAboutTablesOfWaiter,Integer flag)
	{
		Vector<Vector> reportAboutTablesOfThisWaiter = reportAboutTablesOfWaiter;
		detailsPanel = new JPanel();
		PfReportOnTablesAndWaiter	secondTablePanel = new PfReportOnTablesAndWaiter(mainMenu,reportAboutTablesOfThisWaiter,flag);
		detailsPanel.add(secondTablePanel);
		return detailsPanel;
	}
	
	//==================================================================================================================================================	
	
	private JPanel getSecondTablePanel()
	{
		JPanel tablePanel=new JPanel();
		tablePanel.setBackground(new Color(255, 250, 205));
		tablePanel.setForeground(new Color(0, 0, 0));
				
		return tablePanel;
		
		
	}
	
    /**
     * Method for creation JPanel  buttonsPanel and gets two buttons(print and cancel)
     *  from methods getBtnPrnt and getBtnCancel
     * 
     * @return buttonsPanel
     */
	private JPanel getButtonsPanel()
	{
		JPanel buttonsPanel=new JPanel();
		buttonsPanel.setBackground(new Color(255, 250, 205));
		buttonsPanel.setForeground(new Color(0, 0, 0));
		buttonsPanel.setLayout(new BoxLayout(buttonsPanel, BoxLayout.X_AXIS));
		buttonsPanel.add(getBtnPrnt());
		buttonsPanel.add(Box.createHorizontalStrut(10));
		buttonsPanel.add(getBtnCancel());
		buttonsPanel.setPreferredSize(new Dimension(500,500));
		return buttonsPanel;
	}
	
	/**
	 * Method for creation JButton btnPrt for printing of report
	 * @return JButton btnPrt
	 */
	private JButton getBtnPrnt()
	{
		JButton btnPrt=new JButton("הדפס");
		btnPrt.setFont(new Font("Tahoma", Font.BOLD, 14));
		btnPrt.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent e) {
				
					
			}
		});
		
		return btnPrt;
	}
	
	/**
	 * Method for creation JButton btnCancel for return to preview screen
	 * @return JButton btnCancel
	 */
	private JButton getBtnCancel()
	{
		
		JButton btnCancel=new JButton("סגור");
		btnCancel.setFont(new Font("Tahoma", Font.BOLD, 14));
		btnCancel.addActionListener(new java.awt.event.ActionListener() 
		   {
			public void actionPerformed(java.awt.event.ActionEvent e) 
			{		
				((JButton)e.getSource()).getParent().getParent().getParent().remove(((JButton)e.getSource()).getParent().getParent());
				mainMenu.getContentPane().validate();
			}
		});
		return btnCancel;
	}
	
	/**
	 * Method for creation JPanel searchDetails that includes two calendars for choose range of the date 
	 * and JButton refreshBtn which it gets from method getRefreshBtn
	 * @return
	 */
	private JPanel getSearchDetails()
	{
		JPanel searchDetails=new JPanel ();
		searchDetails.setBackground(new Color(255, 245, 238));
		searchDetails.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
		searchDetails.add(getRefreshBtn());
		dateForSearchTo=getOrderDate();
		dateForSearchFrom=getOrderDate();
		
		searchDetails.add(dateForSearchTo);
		searchDetails.add(getToDateLbl());
		
		searchDetails.add(dateForSearchFrom);
		searchDetails.add(getFromDateLbl());
		
		
		return searchDetails;
	}
	
	/**
	 * two methods for creation labels to a calendars of JPanel searchDetails(from and to)
	 * @return JLabel toLbl,FromLbl
	 */
	private JLabel getToDateLbl()
	{
		JLabel ToLbl=new JLabel("   עד  :  ");
		ToLbl.setFont(new Font("Tahoma", Font.PLAIN, 13));
		return ToLbl;
	}
	
	
	
	private JLabel getFromDateLbl()
	{
		JLabel FromLbl=new JLabel("   מ  :  ");
		FromLbl.setFont(new Font("Tahoma", Font.PLAIN, 13));
		return FromLbl;
	}
	
	/**
	 * Method for creation JDatePickerImpl orderDate by using of JDatePicker(calendar)
	 * @return JDatePickerImpl orderDate
	 */
	private JDatePickerImpl getOrderDate()
	{
	 JDatePickerImpl orderDate = (JDatePickerImpl) JDateComponentFactory.createJDatePicker();
	 orderDate.getModel().setSelected(true);
	 return orderDate;
	}
	 
	/**
	 * Method for getting report on tables of waiter and sending it to getDetailsPanel
	 * @param waiterID 
	 * @param flagReportFirstOrReportSecondOfThisWaiter - flag show which report is necessary (on waiter or on table)
	 */
	public void addReportOnTablesOfWaiter(String waiterID,Integer flagReportFirstOrReportSecondOfThisWaiter)
	{
		
		String ID=waiterID;
		if(detailsPanel!=null) this.remove(detailsPanel);
		MessageGetReportOnTablesOfWaiter msgReportTablesOfThisWaiter=new MessageGetReportOnTablesOfWaiter(FromDate,ToDate,ID);
		
		try {
			mainMenu.ms.client.sendToServer(msgReportTablesOfThisWaiter);
			MessageGetReportOnTablesOfWaiterReply resultReport=(MessageGetReportOnTablesOfWaiterReply)mainMenu.ms.client.GetMessage();
			Vector<Vector> report=resultReport.getReport();
			this.add(getDetailsPanel(report,flagReportFirstOrReportSecondOfThisWaiter),BorderLayout.EAST);
			mainMenu.getContentPane().validate();
		}
		catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} 
		
	}
	
	/**
	 * Method for getting report on work days  of waiter and sending it to getDetailsPanel
	 * @param waiterID 
	 * @param flagReportFirstOrReportSecondOfThisWaiter - flag show which report is necessary (on waiter or on table)
	 */
	public void addReportOnWorkDaysOfWaiter (String waiterID,Integer flagReportFirstOrReportSecondOfThisWaiter)
	{
		
		String ID=waiterID;
		if(detailsPanel!=null) this.remove(detailsPanel);
		MessageGetReportWorkHoursOfWaiter msgReportTablesOfThisWaiter=new MessageGetReportWorkHoursOfWaiter(FromDate,ToDate,ID);
		
		try {
			mainMenu.ms.client.sendToServer(msgReportTablesOfThisWaiter);
			MessageGetReportWorkHoursOfWaiterReply resultReport=(MessageGetReportWorkHoursOfWaiterReply)mainMenu.ms.client.GetMessage();
			Vector<Vector> report=resultReport.getReport();
			this.add(getDetailsPanel(report,flagReportFirstOrReportSecondOfThisWaiter),BorderLayout.EAST);
			mainMenu.getContentPane().validate();
		}
		catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} 
		
	}
	
	/**
	 * Method for creation JButton refreshBtn that gets new values of dates(from and to)and refresh the report
	 * @return JButton refreshBtn
	 */
	private JButton getRefreshBtn()
	{
		refreshBtn=new JButton("הצג");
		
		refreshBtn.addActionListener(new java.awt.event.ActionListener() {
			public void actionPerformed(java.awt.event.ActionEvent e) {									
			
				int yearFrom=dateForSearchFrom.getModel().getYear();
				int monthFrom=dateForSearchFrom.getModel().getMonth()+1;
				int dayFrom=dateForSearchFrom.getModel().getDay();
				int yearTo=dateForSearchTo.getModel().getYear();
				int monthTo=dateForSearchTo.getModel().getMonth()+1;
				int dayTo=dateForSearchTo.getModel().getDay();
				
				FromDate=(Integer.toString(yearFrom)+"-"+Integer.toString(monthFrom)+"-"+Integer.toString(dayFrom));
				ToDate=(Integer.toString(yearTo)+"-"+Integer.toString(monthTo)+"-"+Integer.toString(dayTo));
				if(detailsPanel!=null) 
				{
					addReportOnTablesOfWaiter(waiterID,flagReportFirstOrReportSecondOfThisWaiter);
				}
				
				MessageGetReportWaitersByDate msgAllOrders=new MessageGetReportWaitersByDate(FromDate,ToDate);
				try {
					mainMenu.ms.client.sendToServer(msgAllOrders);
					MessageGetReportWaitersByDateReply resultReport=(MessageGetReportWaitersByDateReply)mainMenu.ms.client.GetMessage();
					Vector<Vector> report=resultReport.getReport();
					reportWaiters.removeAllElements();
					for(int i=0 ; i<report.size();i++)
					{
						reportWaiters.add(report.get(i));
					}
					tbl.repaint();
					tbl.validate();
					//refreshTotalPanel();
					mainMenu.getContentPane().validate();
				}
				catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				} 
			
			}

		});
		return refreshBtn;
	}
	
	
	
	
}
